<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>昇腾智能对话助手</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f8f9fa;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            margin: 0;
        }
        
        .navbar {
            background-color: #001529;
            color: white;
            padding: 0.5rem 1rem;
        }
        
        .navbar-brand {
            font-size: 1.4rem;
            font-weight: bold;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            border-radius: 10px;
            margin-top: 1rem;
            padding: 1rem;
            height: calc(100vh - 130px);
        }
        
        .chat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #eee;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .message {
            max-width: 80%;
            padding: 0.8rem 1rem;
            border-radius: 10px;
            position: relative;
            word-wrap: break-word;
        }
        
        .message-user {
            align-self: flex-end;
            background-color: #007bff;
            color: white;
            margin-left: auto;
        }
        
        .message-assistant {
            align-self: flex-start;
            background-color: #f1f1f1;
            color: #333;
            margin-right: auto;
        }
        
        .message-user::after {
            content: "";
            position: absolute;
            right: -10px;
            top: 50%;
            transform: translateY(-50%);
            border: 10px solid transparent;
            border-left-color: #007bff;
        }
        
        .message-assistant::before {
            content: "";
            position: absolute;
            left: -10px;
            top: 50%;
            transform: translateY(-50%);
            border: 10px solid transparent;
            border-right-color: #f1f1f1;
        }
        
        .chat-input-container {
            display: flex;
            margin-top: 1rem;
            padding-top: 0.5rem;
            border-top: 1px solid #eee;
        }
        
        .chat-input {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 0.8rem;
            resize: none;
            height: 60px;
        }
        
        .chat-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        
        .send-button {
            margin-left: 0.5rem;
            border-radius: 5px;
            padding: 0 1.5rem;
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .send-button:hover {
            background-color: #0069d9;
        }
        
        .send-button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .connection-status {
            font-size: 0.85rem;
            color: #666;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .status-connecting {
            background-color: #ffc107;
        }
        
        .status-connected {
            background-color: #28a745;
        }
        
        .status-error {
            background-color: #dc3545;
        }
        
        .settings-panel {
            position: fixed;
            top: 0;
            right: -300px;
            width: 300px;
            height: 100vh;
            background-color: white;
            box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            transition: right 0.3s ease;
            padding: 1rem;
            overflow-y: auto;
        }
        
        .settings-panel.show {
            right: 0;
        }
        
        .settings-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #eee;
        }
        
        .settings-group {
            margin-bottom: 1.5rem;
        }
        
        .settings-group h5 {
            margin-bottom: 0.5rem;
            font-size: 1rem;
            font-weight: 600;
        }
        
        .form-range::-webkit-slider-thumb {
            background: #007bff;
        }
        
        .thinking-animation {
            display: flex;
            gap: 0.3rem;
            align-items: center;
            margin-left: 0.5rem;
        }
        
        .thinking-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: #888;
            animation: thinking 1.4s infinite ease-in-out both;
        }
        
        .thinking-dot:nth-child(1) {
            animation-delay: -0.32s;
        }
        
        .thinking-dot:nth-child(2) {
            animation-delay: -0.16s;
        }
        
        @keyframes thinking {
            0%, 80%, 100% {
                transform: scale(0);
            }
            40% {
                transform: scale(1);
            }
        }
        
        .performance-info {
            font-size: 0.75rem;
            color: #6c757d;
            margin-top: 0.3rem;
        }
        
        @media (max-width: 768px) {
            .chat-container {
                border-radius: 0;
                margin-top: 0;
                height: calc(100vh - 110px);
                width: 100%;
                padding: 0.5rem;
            }
            
            .message {
                max-width: 90%;
            }
            
            .settings-panel {
                width: 85%;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-cpu"></i> 昇腾智能对话助手
            </span>
            <div class="d-flex align-items-center">
                <div class="connection-status me-3">
                    <span class="status-indicator status-connecting" id="statusIndicator"></span>
                    <span id="connectionStatus">连接中...</span>
                </div>
                <button class="btn btn-sm btn-outline-light me-2" id="clearChatBtn">
                    <i class="bi bi-trash"></i> 清空对话
                </button>
                <button class="btn btn-sm btn-outline-light" id="settingsBtn">
                    <i class="bi bi-gear"></i> 设置
                </button>
            </div>
        </div>
    </nav>
    
    <!-- 对话容器 -->
    <div class="container">
        <div class="chat-container">
            <div class="chat-header">
                <h5 class="mb-0">智能对话</h5>
                <div id="modelInfo">基于昇腾处理器的大语言模型</div>
            </div>
            
            <div class="chat-messages" id="chatMessages">
                <!-- 欢迎消息 -->
                <div class="message message-assistant">
                    您好，我是昇腾智能助手，有什么可以帮您解答的问题吗？
                </div>
            </div>
            
            <div class="chat-input-container">
                <textarea 
                    class="chat-input" 
                    id="userInput" 
                    placeholder="请输入您的问题..."
                    rows="2"></textarea>
                <button class="send-button" id="sendBtn">
                    <i class="bi bi-send"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- 设置面板 -->
    <div class="settings-panel" id="settingsPanel">
        <div class="settings-header">
            <h5 class="mb-0">设置</h5>
            <button type="button" class="btn-close" id="closeSettingsBtn"></button>
        </div>
        
        <div class="settings-group">
            <h5>温度 (Temperature)</h5>
            <p class="text-muted small">调整回答的随机性，值越高回答越多样</p>
            <input type="range" class="form-range" min="0" max="1" step="0.01" value="0.7" id="temperatureSlider">
            <div class="d-flex justify-content-between">
                <span>确定性</span>
                <span id="temperatureValue">0.7</span>
                <span>创造性</span>
            </div>
        </div>
        
        <div class="settings-group">
            <h5>最大长度 (Max Length)</h5>
            <p class="text-muted small">设置回答的最大长度</p>
            <input type="range" class="form-range" min="100" max="4000" step="100" value="2000" id="maxLengthSlider">
            <div class="d-flex justify-content-between">
                <span>简短</span>
                <span id="maxLengthValue">2000</span>
                <span>详细</span>
            </div>
        </div>
        
        <div class="settings-group">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="showPerformanceCheck">
                <label class="form-check-label" for="showPerformanceCheck">显示性能信息</label>
            </div>
            <p class="text-muted small">开启后将显示推理时间和Token数量等信息</p>
        </div>
    </div>
    
    <!-- JS脚本 -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 元素引用
            const chatMessages = document.getElementById('chatMessages');
            const userInput = document.getElementById('userInput');
            const sendBtn = document.getElementById('sendBtn');
            const clearChatBtn = document.getElementById('clearChatBtn');
            const settingsBtn = document.getElementById('settingsBtn');
            const settingsPanel = document.getElementById('settingsPanel');
            const closeSettingsBtn = document.getElementById('closeSettingsBtn');
            const connectionStatus = document.getElementById('connectionStatus');
            const statusIndicator = document.getElementById('statusIndicator');
            const modelInfo = document.getElementById('modelInfo');
            
            // 设置相关元素
            const temperatureSlider = document.getElementById('temperatureSlider');
            const temperatureValue = document.getElementById('temperatureValue');
            const maxLengthSlider = document.getElementById('maxLengthSlider');
            const maxLengthValue = document.getElementById('maxLengthValue');
            const showPerformanceCheck = document.getElementById('showPerformanceCheck');
            
            // 全局变量
            let conversationHistory = [];
            let isProcessing = false;
            
            // 初始化
            checkServiceHealth();
            
            // 设置值初始化
            temperatureValue.textContent = temperatureSlider.value;
            maxLengthValue.textContent = maxLengthSlider.value;
            
            // 事件监听
            userInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    if (!isProcessing && userInput.value.trim() !== '') {
                        sendMessage();
                    }
                }
            });
            
            sendBtn.addEventListener('click', function() {
                if (!isProcessing && userInput.value.trim() !== '') {
                    sendMessage();
                }
            });
            
            clearChatBtn.addEventListener('click', clearChat);
            
            settingsBtn.addEventListener('click', function() {
                settingsPanel.classList.add('show');
            });
            
            closeSettingsBtn.addEventListener('click', function() {
                settingsPanel.classList.remove('show');
            });
            
            temperatureSlider.addEventListener('input', function() {
                temperatureValue.textContent = this.value;
            });
            
            maxLengthSlider.addEventListener('input', function() {
                maxLengthValue.textContent = this.value;
            });
            
            // 检查服务健康状态
            function checkServiceHealth() {
                connectionStatus.textContent = '正在连接...';
                statusIndicator.className = 'status-indicator status-connecting';
                
                fetch('/api/proxy/health')
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'ok') {
                            connectionStatus.textContent = '已连接';
                            statusIndicator.className = 'status-indicator status-connected';
                            
                            // 显示模型信息
                            if (data.model_path && data.device) {
                                modelInfo.textContent = `模型: ${data.model_path.split('/').pop()} | 设备: ${data.device}`;
                            }
                        } else {
                            connectionStatus.textContent = '连接失败: ' + (data.reason || '未知错误');
                            statusIndicator.className = 'status-indicator status-error';
                        }
                    })
                    .catch(error => {
                        connectionStatus.textContent = '连接错误';
                        statusIndicator.className = 'status-indicator status-error';
                        console.error('健康检查错误:', error);
                    });
            }
            
            // 发送消息
            function sendMessage() {
                const message = userInput.value.trim();
                if (message === '') return;
                
                // 添加用户消息到聊天界面
                addMessageToChat('user', message);
                
                // 清空输入框
                userInput.value = '';
                
                // 添加思考动画
                const thinkingMsg = addThinkingAnimation();
                
                // 设置状态
                isProcessing = true;
                sendBtn.disabled = true;
                
                // 准备请求数据
                const requestData = {
                    messages: buildMessages(message),
                    temperature: parseFloat(temperatureSlider.value),
                    max_length: parseInt(maxLengthSlider.value),
                    show_performance: showPerformanceCheck.checked
                };
                
                // 发送请求
                fetch('/api/proxy/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('请求失败: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    // 移除思考动画
                    if (thinkingMsg) {
                        chatMessages.removeChild(thinkingMsg);
                    }
                    
                    // 添加助手回复
                    addMessageToChat('assistant', data.response, data.performance);
                    
                    // 更新对话历史
                    conversationHistory.push({ role: 'user', content: message });
                    conversationHistory.push({ role: 'assistant', content: data.response });
                })
                .catch(error => {
                    // 移除思考动画
                    if (thinkingMsg) {
                        chatMessages.removeChild(thinkingMsg);
                    }
                    
                    // 显示错误消息
                    addMessageToChat('assistant', '抱歉，发生了错误: ' + error.message);
                    console.error('API请求错误:', error);
                })
                .finally(() => {
                    // 重置状态
                    isProcessing = false;
                    sendBtn.disabled = false;
                    userInput.focus();
                });
            }
            
            // 添加消息到聊天界面
            function addMessageToChat(role, content, performance = null) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message message-${role}`;
                
                // 处理换行
                const formattedContent = content.replace(/\n/g, '<br>');
                messageDiv.innerHTML = formattedContent;
                
                // 添加性能信息
                if (role === 'assistant' && performance && showPerformanceCheck.checked) {
                    const perfDiv = document.createElement('div');
                    perfDiv.className = 'performance-info';
                    const inTokens = performance.input_tokens || 0;
                    const outTokens = performance.output_tokens || 0;
                    const time = performance.time || 0;
                    const speed = performance.tokens_per_second || 0;
                    
                    perfDiv.textContent = `输入: ${inTokens} tokens | 输出: ${outTokens} tokens | 用时: ${time.toFixed(2)}s | 速度: ${speed.toFixed(2)} t/s`;
                    messageDiv.appendChild(perfDiv);
                }
                
                chatMessages.appendChild(messageDiv);
                
                // 滚动到底部
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                return messageDiv;
            }
            
            // 添加思考动画
            function addThinkingAnimation() {
                const thinkingDiv = document.createElement('div');
                thinkingDiv.className = 'message message-assistant';
                thinkingDiv.style.display = 'flex';
                thinkingDiv.style.alignItems = 'center';
                
                const textSpan = document.createElement('span');
                textSpan.textContent = '思考中';
                thinkingDiv.appendChild(textSpan);
                
                const animDiv = document.createElement('div');
                animDiv.className = 'thinking-animation';
                
                for (let i = 0; i < 3; i++) {
                    const dot = document.createElement('div');
                    dot.className = 'thinking-dot';
                    animDiv.appendChild(dot);
                }
                
                thinkingDiv.appendChild(animDiv);
                chatMessages.appendChild(thinkingDiv);
                
                // 滚动到底部
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                return thinkingDiv;
            }
            
            // 构建消息历史
            function buildMessages(currentMessage) {
                // 复制现有历史
                const messages = [...conversationHistory];
                
                // 添加当前消息
                messages.push({ role: 'user', content: currentMessage });
                
                return messages;
            }
            
            // 清空聊天
            function clearChat() {
                // 清空历史记录
                conversationHistory = [];
                
                // 清空聊天界面，只保留欢迎消息
                chatMessages.innerHTML = '';
                addMessageToChat('assistant', '您好，我是昇腾智能助手，有什么可以帮您解答的问题吗？');
            }
        });
    </script>
</body>
</html> 